package top.letscode.adclicker.executor;

import java.util.List;

import org.openqa.selenium.WebDriver;

import top.letscode.adclicker.ad.AbstractUnion;
import top.letscode.adclicker.ad.AdRuleChecker;
import top.letscode.adclicker.annotation.Union;
import top.letscode.adclicker.driver.ChromeDriverFactory;
import top.letscode.adclicker.driver.WebDriverHelper;
import top.letscode.adclicker.site.AbstractSite;
import top.letscode.adclicker.store.SimpleDataStore;
import top.letscode.adclicker.util.Constants;
import top.letscode.adclicker.util.RandomUtil;
import top.letscode.adclicker.util.Utils;

public class AdExecutor implements Runnable {

  private AbstractUnion union;
  private AbstractSite site;

  public AdExecutor(AbstractUnion union, AbstractSite site) {
    this.union = union;
    this.site = site;
  }

  private String getRandomUrl() {
    List<String> urls = (List<String>) SimpleDataStore.getFileLines(Constants.STORE_ANNOTATION_SITE,
        site.getUrlFileName());
    return RandomUtil.random(urls);
  }

  private String getUnionType() {
    return union.getClass().getAnnotation(Union.class).type();
  }

  @Override
  public void run() {

    while (true) {
      // SetResUtil.changeScreenResolution();
      WebDriver webDriver = null;

      // 随机点击N个页面
      try {
        webDriver = ChromeDriverFactory.newInstance(getUnionType());
        for (int i = 0; i < 1 + RandomUtil.randomInt(3) + RandomUtil.randomInt(3); i++) {
          WebDriverHelper.checkAlertPresent(webDriver);
          union.open(webDriver, getRandomUrl());
          Utils.sleepQuietly(RandomUtil.randomInt(2) + 1);
          if (AdRuleChecker.canClick(union)) {
            union.click(webDriver);
            Utils.sleepQuietly(1);
          }

          WebDriverHelper.checkAlertPresent(webDriver);
        }
      } catch (Exception e) {

      } finally {
        WebDriverHelper.close(webDriver);
      }

      // 执行完毕线程休眠，凌晨时刻休眠时间要长一些
      int sleepSecond = 1;
      if (Utils.isInMorning()) {
        sleepSecond += RandomUtil.randomInt(10) + 5;
      }
      Utils.sleepQuietly(sleepSecond);
    }
  }
}
